package com.wyu.service;


import com.wyu.dao.MenuMapper;

import com.wyu.dao.OrderItemMapper;
import com.wyu.dao.OrderMapper;

import com.wyu.pojo.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class OrderServiceImpl implements OrderService {

    private OrderMapper orderMapper;
    private OrderItemMapper orderItemMapper;
    private MenuMapper menuMapper ;


    public void setOrderMapper(OrderMapper orderMapper) {
        this.orderMapper = orderMapper;
    }
    public void setOrderItemMapper(OrderItemMapper orderItemMapper) {
        this.orderItemMapper = orderItemMapper;
    }
    public void setMenuMapper(MenuMapper menuMapper) {
        this.menuMapper = menuMapper;
    }

    @Override
    public String createOrder(Cart cart, Integer userId) {
        // 订单号===唯一性
        //System.currentTimeMillis返回的是从1970.1.1 UTC 零点开始到现在的时间，精确到毫秒
        String orderId = System.currentTimeMillis()+""+userId;
        Date current = new Date();
        SimpleDateFormat dateFormat = new   SimpleDateFormat("yyyy-MM-dd");
        // 创建一个订单对象
        System.out.println(dateFormat.format(current));
        Order order = new Order(orderId,dateFormat.format(current),cart.getTotalPrice(), 0,userId);
        // 保存订单
        orderMapper.saveOrder(order);

        // 遍历购物车中每一个商品项转换成为订单项保存到数据库
        for (Map.Entry<Integer, CartItem>entry : cart.getItems().entrySet()){
            // 获取每一个购物车中的商品项
            CartItem cartItem = entry.getValue();
            // 转换为每一个订单项
            OrderItem orderItem = new OrderItem(null,cartItem.getName(),cartItem.getCount(),cartItem.getPrice(),cartItem.getTotalPrice(), orderId);
            // 保存订单项到数据库
            orderItemMapper.saveOrderItem(orderItem);

            // 更新库存和销量
            menu menu = menuMapper.queryMenuById(cartItem.getId());
            menu.setSales( menu.getSales() + cartItem.getCount() );
            menu.setStock( menu.getStock() - cartItem.getCount() );
            menuMapper.updateMenu(menu);

        }
        // 清空购物车
        cart.clear();

        return orderId;
    }
    @Override
    public List<Order> showAllOrders(){return orderMapper.queryOrders();}
    // 0未配送，1已配送，2表示已签收
    @Override
    public int sendOrder(String id){return  orderMapper.changeOrderStatus(id,1);}
    @Override
    public List<OrderItem> showOrderDetail(String id){return orderItemMapper.queryOrderItemsByOrderId(id);}
    @Override
    public List<Order> showMyOrders(Integer id){return orderMapper.queryOrdersByUserId(id);}
    @Override
    public int receiverOrder(String id){return orderMapper.changeOrderStatus(id,2);}
}
